package com.gitee.chenyaohua.demo.mybatis.encryption.decryption.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.nio.charset.Charset;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Base64;

/** 数据库中的数据类型 */
@MappedJdbcTypes(value = JdbcType.VARCHAR)
/** 处理后的数据类型 */
@MappedTypes(value = String.class)
public class EncrptionOrDecryptionTypeHandler extends BaseTypeHandler<String> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            ps.setString(i,null);
            return ;

        }
        ps.setString(i,Base64.getEncoder().encodeToString(parameter.getBytes(Charset.defaultCharset())));
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return decode(rs.getString(columnName));
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return decode(rs.getString(columnIndex));
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return decode(cs.getString(columnIndex));
    }

    public String decode(String val){
        if(val == null){
            return null;
        }
        byte[] decode = Base64.getDecoder().decode(val.getBytes(Charset.defaultCharset()));
        return new String(decode,Charset.defaultCharset());
    }

}
